import { IBuildTaskOption, BuildHook, IBuildResult } from '../@types';
import fs from 'fs';
import path from 'path';
interface IOptions {
    encodeKey:number //加密key
}

const PACKAGE_NAME = 'encrypic';
const projectPath = Editor.Project.path;
interface ITaskOptions extends IBuildTaskOption {
    packages: {
        'cocos-plugin-template': IOptions;
    };
}
function log(...arg: any[]) {
    return console.log(`[${PACKAGE_NAME}] `, ...arg);
}

let allAssets = [];

export const throwError: BuildHook.throwError = true;

export const load: BuildHook.load = async function() {
    console.log(`[${PACKAGE_NAME}] Load cocos plugin example in builder.`);
    allAssets = await Editor.Message.request('asset-db', 'query-assets');
};

export const onBeforeBuild: BuildHook.onBeforeBuild = async function(options: ITaskOptions, result: IBuildResult) {
    // Todo some thing
    log(`${PACKAGE_NAME}.webTestOption`, 'onBeforeBuild');
    //修改代码里面的加密秘钥
    var file = `${projectPath}/assets/webGame/Config/decrypt_plugin.js`;
    //判断文件是否存在
    if(fs.existsSync(file))
    {
        var data = fs.readFileSync(file,'utf-8');
        var param:IOptions = options.packages[PACKAGE_NAME];
        var encodeKey = param.encodeKey
        //替换文件里面的encryptKey=整数
        const newData = data.replace(/encryptKey=\d+/g, `encryptKey=${encodeKey}`);
        fs.writeFileSync(file,newData);
    }
};

export const onBeforeCompressSettings: BuildHook.onBeforeCompressSettings = async function(options: ITaskOptions, result: IBuildResult) {
    const pkgOptions = options.packages[PACKAGE_NAME];
    if (pkgOptions.webTestOption) {
        console.debug('webTestOption', true);
    }
    // Todo some thing
    console.debug('get settings test', result.settings);
};

export const onAfterCompressSettings: BuildHook.onAfterCompressSettings = async function(options: ITaskOptions, result: IBuildResult) {
    // Todo some thing
    console.log('webTestOption', 'onAfterCompressSettings');
};

export const onAfterBuild: BuildHook.onAfterBuild = async function(options: ITaskOptions, result: IBuildResult) {
    log(`${PACKAGE_NAME}`, 'onAfterBuild====++' + JSON.stringify(result.paths));
    log(`${PACKAGE_NAME}`, 'onAfterBuild====++' + JSON.stringify(result.settings));
    if(!result.settings.engine.debug)
    {
        EncryPic(options,result);
    }
    // Editor.Message.broadcast("onAfterBuild");
};

export const unload: BuildHook.unload = async function() {
    console.log(`[${PACKAGE_NAME}] Unload cocos plugin example in builder.`);
};

export const onError: BuildHook.onError = async function(options, result) {
    // Todo some thing
    console.warn(`${PACKAGE_NAME} run onError`);
};

export const onBeforeMake: BuildHook.onBeforeMake = async function(root, options) {
    console.log(`onBeforeMake: root: ${root}, options: ${options}`);
};

export const onAfterMake: BuildHook.onAfterMake = async function(root, options) {
    console.log(`onAfterMake: root: ${root}, options: ${options}`);
};

/**
 * 加密图片
 * @param dirPath 
 */
const encryptType = [".png",".webp",".jpg",".pkm"] //加密类型
const EncryPic = function(options: ITaskOptions,result:IBuildResult){
    var dirPath = result.dest

    var param:IOptions = options.packages[PACKAGE_NAME];
    var encodeKey = param.encodeKey
    //遍历目录下面的文件
    let allFiles = listFiles(dirPath);
    //看文件是不是在加密类型里面
    allFiles.forEach((filePath)=>{
        let extname = path.extname(filePath);
        if(encryptType.indexOf(extname) != -1){
            //加密文件
            if(encodeKey>0)
            {
                encryptFile(filePath,encodeKey);
            }
            
        }
    })
}

/**
 * 加密文件
 * @param filePath 
 * @param encodeKey
 */
const encryptFile = function(filePath:string,encodeKey:number){
    fs.readFile(filePath,(err, data) => {
        if (err) {
            
        } else {

            var arrayBuffer = new Uint8Array(data);

            //每个数据异或2
            for (let i = 0; i < arrayBuffer.length; i++) {
                arrayBuffer[i] = arrayBuffer[i] ^ encodeKey
            }

            fs.writeFile(filePath,arrayBuffer,(err)=>{
                if(err)
                {
                    console.log('write error',err);
                }
                else
                {
                    console.log('write success');
                }
            })
        }
    });
}
/**
 * 获取目录下面的所有文件
 * @param assetPath 
 * @returns 
 */
const listFiles = (assetPath: string): string[]=> {
    var fileList = [];
    var stat = fs.statSync(assetPath);
    if (stat.isDirectory()) {
        var subpaths = fs.readdirSync(assetPath);
        for (var i = 0; i < subpaths.length; i++) {
            var subpath = subpaths[i];
            if (subpath[0] === '.') {
                continue;
            }
            subpath = path.join(assetPath, subpath);
            fileList.push(...listFiles(subpath));
        }
    }
    else if (stat.isFile()) {
        fileList.push(assetPath);
    }
    return fileList;
}
